package org.juggers.server;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @author <a href="mailto:michel@breizhjug.org">Michel DAVID</a>
 */
public class CaptchaCheck
{
    //private static Log logger = LogFactory.getLog( CaptchaCheck.class );

    // reCaptcha "invalid solution" error
    private static final String INVALID_SOLUTION = "incorrect-captcha-sol";

    private String privateKey = Configuration.getInstance().getReCaptchaKey();

    public boolean isValid( String challenge, String response, String remoteAddr )
    {
        try
        {
            URL url = new URL( "http://api-verify.recaptcha.net/verify" );
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput( true );
            connection.setRequestMethod( "POST" );

            OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream() );
            writer.write( getPostParameters( challenge, response, remoteAddr ) );
            writer.close();

            if ( connection.getResponseCode() == HttpURLConnection.HTTP_OK )
            {
                BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
                try
                {
                    boolean valid = Boolean.parseBoolean( reader.readLine() );
                    if ( valid )
                    {
                        return true;
                    }

                    String errorCode = reader.readLine();
                    if ( !INVALID_SOLUTION.equals( errorCode ) )
                    {
                        //logger.error( "reCaptcha Error " + errorCode );
                    }
                }
                finally
                {
                    reader.close();
                }
            }
            else
            {
                //logger.error( "reCaptcha HTTP Error " + connection.getResponseCode() );
            }
        }
        catch ( MalformedURLException ex )
        {
            //logger.error( "reCaptcha MalformedURLException " + ex.getMessage() );
        }
        catch ( IOException ex )
        {
            //logger.error( "reCaptcha IOException " + ex.getMessage() );
        }
        return false;
    }

    private String getPostParameters( String challenge, String response, String remoteAddr )
        throws UnsupportedEncodingException
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append( "privatekey=" ).append( URLEncoder.encode( privateKey, "UTF-8" ) );
        buffer.append( "&remoteip=" ).append( URLEncoder.encode( remoteAddr, "UTF-8" ) );
        buffer.append( "&challenge=" ).append( URLEncoder.encode( challenge, "UTF-8" ) );
        buffer.append( "&response=" ).append( URLEncoder.encode( response, "UTF-8" ) );
        return buffer.toString();
    }

    public void setPrivateKey( String privateKey )
    {
        this.privateKey = privateKey;
    }
}
